< previous page page_148 next page >

Page 148
Using Visual Basic and API drawing methods, you can print anything you can display on a form or picture box at the printer's full resolution. To produce high-quality output, however, there are still a couple of details you must be prepared to handle.
Printing Text
Using the Printer object's CurrentX and CurrentY properties and its Print method, you can print text. The Print command knows nothing about margins, however. If you print a very long string using the Print statement, the text will extend off the right side of the printed page and be truncated. If you want text to wrap when it reaches the printer's right margin, you must write code to control the positioning of each word.
The simplest way to wrap text is to examine the string one word at a time. For each word, use the Printer object's TextWidth function to see how wide the word will be on the printer. If that width added to CurrentX is greater than the right margin, start a new line.
Similarly, when the program starts a new line, it should check the Printer object's CurrentY property to see if there is room for the next line of text. If there is no more room on the page, the program can use the NewPage method to start a new page.
After examining the new word, possibly starting a new line or page, the program should use the Print statement to display the word.
Example program WordWrap uses this technique to print text. The program also supports simple paragraph formatting. When it finds a carriage return and line feed combination, it starts a new paragraph by skipping some extra vertical space and indenting the paragraph's first word.
Program WordWrap uses the PrintWrappedText subroutine, shown in the following code, to print text on an object. This routine repeatedly searches the text for carriage return and line feed pairs to see where the first paragraph ends. It removes the paragraph from the text and increases CurrentX to indent the paragraph.
It then repeatedly searches the paragraph for a space character to see where the first word ends. It removes the word from the paragraph.
The routine adds the word's length to the Printer object's CurrentX property to see if there is room for the word. If there is no more room on the line, the program starts a new line and determines whether there is room for the new line on the current page. If there is no more room on the page, then PrintWrappedText starts a new page.
e10a6a0a59f035e870d90cca05b85fce.gif
' Print a string on a Printer or PictureBox,
' wrapped within the margins.
Private Sub PrintWrappedText(ByVal txt As String, _
    ByVal indent As Single, _
    ByVal left_margin As Single, _
    ByVal top_margin As Single, _
    ByVal right_margin As Single, _

 
< previous page page_148 next page >